package client

import (
	"context"
	"errors"
	"log"

	"aqielife.cn/spider/singleSpider/zhenaiDistributed/config"
	"aqielife.cn/spider/singleSpider/zhenaiDistributed/engine"
	"aqielife.cn/spider/singleSpider/zhenaiDistributed/rpcsupport"
	elastic "github.com/olivere/elastic/v7"
)

func ItemSaver(host string) (chan engine.Item, error) {

	client, err := rpcsupport.NewClient(host)
	if err != nil {
		return nil, err
	}
	out := make(chan engine.Item)
	go func() {
		itemCount := 0
		for {
			item := <-out
			log.Printf("Item Saver: go item #%d: %v", itemCount, item)
			itemCount++
			result := ""
			err = client.Call(config.ItemSaveRpc, item, &result)
			if err != nil {
				log.Printf("result: %s; error: %s",
					item, err)
			}
		}
	}()
	return out, nil
}

func Save(client *elastic.Client, index string,
	item engine.Item) error {

	if item.Type == "" {
		return errors.New("must supply Type")
	}
	indexService := client.Index().Index(index).
		Type(item.Type).BodyJson(item)
	if item.Id != "" {
		indexService.Id(item.Id)
	}
	_, err := indexService.Do(context.Background())
	if err != nil {
		return err
	}

	return nil
}
